using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using System.Transactions;
using JGSY.CMS.LowCode.Platform.Domain.Enums;

namespace JGSY.CMS.LowCode.Platform.Application.Services
{
    /// <summary>
    /// 工作流应用服务实现
    /// 提供完整的工作流生命周期管理，包括工作流定义、实例管理、任务执行、版本控制等核心功能
    /// 支持工作流的创建、启动、执行、监控、暂停、恢复、终止等业务场景
    /// 集成版本管理、任务调度、状态跟踪、性能监控等企业级特性
    /// </summary>
    public class WorkflowAppService : IWorkflowAppService
    {
        /// <summary>
        /// 工作流定义数据仓储
        /// </summary>
        private readonly IWorkflowRepository _workflowRepository;
        
        /// <summary>
        /// 工作流实例数据仓储
        /// </summary>
        private readonly IWorkflowInstanceRepository _workflowInstanceRepository;
        
        /// <summary>
        /// 工作流任务数据仓储
        /// </summary>
        private readonly IWorkflowTaskRepository _workflowTaskRepository;
        
        /// <summary>
        /// 工作流版本数据仓储
        /// </summary>
        private readonly IWorkflowVersionRepository _workflowVersionRepository;
        
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<WorkflowAppService> _logger;
        
        /// <summary>
        /// 监控服务，用于性能监控和指标收集
        /// </summary>
        private readonly IMonitorService? _monitorService;
        
        /// <summary>
        /// 版本控制最大重试次数
        /// </summary>
        private readonly int _versioningMaxRetries;
        
        /// <summary>
        /// 版本控制基础退避时间（毫秒）
        /// </summary>
        private readonly int _versioningBaseBackoffMs;
        
        /// <summary>
        /// 版本控制抖动时间（毫秒）
        /// </summary>
        private readonly int _versioningJitterMs;

        /// <summary>
        /// 初始化工作流应用服务实例
        /// </summary>
        /// <param name="workflowRepository">工作流定义数据仓储</param>
        /// <param name="workflowInstanceRepository">工作流实例数据仓储</param>
        /// <param name="workflowTaskRepository">工作流任务数据仓储</param>
        /// <param name="workflowVersionRepository">工作流版本数据仓储</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="configuration">配置服务</param>
        /// <param name="monitorService">监控服务</param>
        /// <exception cref="ArgumentNullException">当必要的依赖项为null时抛出</exception>
        public WorkflowAppService(
            IWorkflowRepository workflowRepository,
            IWorkflowInstanceRepository workflowInstanceRepository,
            IWorkflowTaskRepository workflowTaskRepository,
            IWorkflowVersionRepository workflowVersionRepository,
            ILogger<WorkflowAppService> logger,
            IConfiguration? configuration = null,
            IMonitorService? monitorService = null)
        {
            _workflowRepository = workflowRepository ?? throw new ArgumentNullException(nameof(workflowRepository));
            _workflowInstanceRepository = workflowInstanceRepository ?? throw new ArgumentNullException(nameof(workflowInstanceRepository));
            _workflowTaskRepository = workflowTaskRepository ?? throw new ArgumentNullException(nameof(workflowTaskRepository));
            _workflowVersionRepository = workflowVersionRepository ?? throw new ArgumentNullException(nameof(workflowVersionRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _monitorService = monitorService;

            _versioningMaxRetries = configuration?.GetValue<int?>("Workflow:Versioning:Retries") ?? 2;
            _versioningBaseBackoffMs = configuration?.GetValue<int?>("Workflow:Versioning:BaseBackoffMs") ?? 50;
            _versioningJitterMs = configuration?.GetValue<int?>("Workflow:Versioning:JitterMs") ?? 25;
        }

        /// <summary>
        /// 创建工作流
        /// </summary>
        public async Task<WorkflowDto> CreateAsync(WorkflowDto workflowDto)
        {
            try
            {
                // 验证工作流
                var validation = await ValidateWorkflowAsync(workflowDto);
                if (!validation.IsValid)
                {
                    throw new ArgumentException($"工作流验证失败: {string.Join(", ", validation.Errors)}");
                }

                // 检查标识符重复
                if (!string.IsNullOrEmpty(workflowDto.Identifier))
                {
                    var exists = await IdentifierExistsAsync(workflowDto.Identifier);
                    if (exists)
                    {
                        throw new ArgumentException($"工作流标识符已存在: {workflowDto.Identifier}");
                    }
                }

                var workflow = new Workflow
                {
                    Name = workflowDto.Name,
                    Steps = workflowDto.Definition ?? string.Empty,
                    Conditions = workflowDto.Conditions ?? string.Empty,
                    CreatedBy = 1, // 这里需要从上下文获取当前用户ID
                    CreatedAt = DateTime.UtcNow
                };

                await _workflowRepository.AddAsync(workflow);
                await _workflowRepository.SaveChangesAsync();

                _logger.LogInformation("工作流创建成功: {Name}", workflowDto.Name);
                return MapToDto(workflow);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建工作流失败: {Name}", workflowDto.Name);
                throw;
            }
        }

        /// <summary>
        /// 更新工作流
        /// </summary>
        public async Task<WorkflowDto?> UpdateAsync(WorkflowDto workflowDto)
        {
            try
            {
                var workflow = await _workflowRepository.GetByIdAsync(workflowDto.Id);
                if (workflow == null)
                {
                    throw new ArgumentException($"工作流不存在: {workflowDto.Id}");
                }

                // 验证工作流
                var validation = await ValidateWorkflowAsync(workflowDto);
                if (!validation.IsValid)
                {
                    throw new ArgumentException($"工作流验证失败: {string.Join(", ", validation.Errors)}");
                }

                // 检查标识符重复
                if (!string.IsNullOrEmpty(workflowDto.Identifier))
                {
                    var exists = await IdentifierExistsAsync(workflowDto.Identifier, workflowDto.Id);
                    if (exists)
                    {
                        throw new ArgumentException($"工作流标识符已存在: {workflowDto.Identifier}");
                    }
                }

                workflow.Name = workflowDto.Name;
                workflow.Steps = workflowDto.Definition ?? string.Empty;
                workflow.Conditions = workflowDto.Conditions ?? string.Empty;

                await _workflowRepository.SaveChangesAsync();

                _logger.LogInformation("工作流更新成功: {Name}", workflowDto.Name);
                return MapToDto(workflow);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新工作流失败: {Id}", workflowDto.Id);
                throw;
            }
        }

        /// <summary>
        /// 删除工作流
        /// </summary>
        public async Task<bool> DeleteAsync(long id)
        {
            try
            {
                var workflow = await _workflowRepository.GetByIdAsync(id);
                if (workflow == null)
                {
                    return false;
                }

                // 检查是否有运行中的实例
                var runningInstances = await _workflowInstanceRepository.GetByWorkflowIdAsync(id);
                var hasRunningInstances = runningInstances.Any(x => x.Status == WorkflowInstanceStatus.Running);

                if (hasRunningInstances)
                {
                    throw new InvalidOperationException("无法删除工作流，存在运行中的实例");
                }

                await _workflowRepository.DeleteAsync(workflow);
                await _workflowRepository.SaveChangesAsync();

                _logger.LogInformation("工作流删除成功: {Id}", id);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除工作流失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 批量删除工作流
        /// </summary>
        public async Task<int> BatchDeleteAsync(IEnumerable<long> ids)
        {
            try
            {
                int deletedCount = 0;
                foreach (var id in ids)
                {
                    if (await DeleteAsync(id))
                    {
                        deletedCount++;
                    }
                }

                _logger.LogInformation("批量删除工作流完成，删除数量: {Count}", deletedCount);
                return deletedCount;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除工作流失败");
                throw;
            }
        }

        /// <summary>
        /// 根据ID获取工作流
        /// </summary>
        public async Task<WorkflowDto?> GetByIdAsync(long id)
        {
            try
            {
                var workflow = await _workflowRepository.GetByIdAsync(id);
                return workflow == null ? null : MapToDto(workflow);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 根据标识符获取工作流
        /// </summary>
        public async Task<WorkflowDto?> GetByIdentifierAsync(string identifier)
        {
            try
            {
                var workflow = await _workflowRepository.GetByCodeAsync(identifier);
                return workflow == null ? null : MapToDto(workflow);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据标识符获取工作流失败: {Identifier}", identifier);
                throw;
            }
        }

        /// <summary>
        /// 获取所有工作流
        /// </summary>
        public async Task<IEnumerable<WorkflowDto>> GetAllAsync()
        {
            try
            {
                var workflows = await _workflowRepository.GetAllAsync();
                return workflows.Select(MapToDto);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有工作流失败");
                throw;
            }
        }

        /// <summary>
        /// 分页获取工作流
        /// </summary>
        public async Task<(IEnumerable<WorkflowDto> Items, int TotalCount)> GetPagedAsync(int pageIndex, int pageSize, string? keyword = null, string? category = null, byte? status = null)
        {
            try
            {
                // 构建查询条件
                var query = await _workflowRepository.FindAsync(w => 
                    (string.IsNullOrEmpty(keyword) || w.Name.Contains(keyword)) &&
                    (string.IsNullOrEmpty(category) || w.Name.Contains(category)) // 简化实现，实际应该有Category字段
                );

                var totalCount = query.Count();
                var items = query
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .Select(MapToDto)
                    .ToList();

                return (items, totalCount);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分页获取工作流失败");
                throw;
            }
        }

        /// <summary>
        /// 分页获取工作流（接口兼容方法）
        /// </summary>
        public async Task<(IEnumerable<WorkflowDto> Items, int TotalCount)> GetPagedAsync(int pageIndex = 1, int pageSize = 20, string? name = null, string? category = null)
        {
            return await GetPagedAsync(pageIndex, pageSize, name, category, null);
        }

        /// <summary>
        /// 根据分类获取工作流
        /// </summary>
        public async Task<IEnumerable<WorkflowDto>> GetByCategoryAsync(string category)
        {
            try
            {
                var workflows = await _workflowRepository.GetByCategoryAsync(category);
                return workflows.Select(MapToDto);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据分类获取工作流失败: {Category}", category);
                throw;
            }
        }

        /// <summary>
        /// 获取活跃工作流
        /// </summary>
        public async Task<IEnumerable<WorkflowDto>> GetActiveWorkflowsAsync()
        {
            try
            {
                var workflows = await _workflowRepository.GetPublishedWorkflowsAsync();
                return workflows.Select(MapToDto);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取活跃工作流失败");
                throw;
            }
        }

        /// <summary>
        /// 获取运行中的工作流
        /// </summary>
        public async Task<IEnumerable<WorkflowDto>> GetRunningWorkflowsAsync()
        {
            try
            {
                // 获取有运行中实例的工作流
                var runningInstances = await _workflowInstanceRepository.FindAsync(x => x.Status == WorkflowInstanceStatus.Running);
                var workflowIds = runningInstances.Select(x => x.WorkflowId).Distinct();
                
                var workflows = await _workflowRepository.FindAsync(w => workflowIds.Contains(w.Id));
                return workflows.Select(MapToDto);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取运行中工作流失败");
                throw;
            }
        }

        /// <summary>
        /// 搜索工作流
        /// </summary>
        public async Task<(IEnumerable<WorkflowDto> Items, int TotalCount)> SearchAsync(string keyword, int pageIndex = 1, int pageSize = 20)
        {
            try
            {
                var query = await _workflowRepository.FindAsync(w => 
                    w.Name.Contains(keyword) || 
                    w.Steps.Contains(keyword));

                var totalCount = query.Count();
                var items = query
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .Select(MapToDto)
                    .ToList();

                return (items, totalCount);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索工作流失败: {Keyword}", keyword);
                throw;
            }
        }

        /// <summary>
        /// 启动工作流
        /// </summary>
        public async Task<string?> StartWorkflowAsync(long id, Dictionary<string, object>? inputData = null, long? userId = null)
        {
            try
            {
                var workflow = await _workflowRepository.GetByIdAsync(id);
                if (workflow == null)
                {
                    throw new ArgumentException($"工作流不存在: {id}");
                }

                // 创建工作流实例
                var instance = new WorkflowInstance
                {
                    WorkflowId = id,
                    InstanceName = $"{workflow.Name}_Instance_{DateTime.Now:yyyyMMddHHmmss}",
                    Status = WorkflowInstanceStatus.Running,
                    CurrentNode = "StartNode", // 开始节点
                    InitiatorId = userId ?? 1,
                    ContextData = JsonSerializer.Serialize(inputData ?? new Dictionary<string, object>()),
                    Description = $"工作流实例 - {workflow.Name}",
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                };

                await _workflowInstanceRepository.AddAsync(instance);
                await _workflowInstanceRepository.SaveChangesAsync();

                // 增加执行次数
                await _workflowRepository.IncrementExecutionCountAsync(id);

                _logger.LogInformation("工作流启动成功: {WorkflowId}, InstanceId: {InstanceId}", id, instance.Id);
                return instance.Id.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "启动工作流失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 启动工作流（接口兼容方法）
        /// </summary>
        async Task<long> IWorkflowAppService.StartWorkflowAsync(long id, Dictionary<string, object>? inputData, long? userId)
        {
            var instanceId = await StartWorkflowAsync(id, inputData, userId);
            return long.TryParse(instanceId, out long result) ? result : 0;
        }

        /// <summary>
        /// 停止工作流
        /// </summary>
        public async Task<bool> StopWorkflowAsync(long id, string? reason = null)
        {
            try
            {
                // 停止所有运行中的实例
                var runningInstances = await _workflowInstanceRepository.GetByWorkflowIdAsync(id);
                var activeInstances = runningInstances.Where(x => x.Status == WorkflowInstanceStatus.Running);

                foreach (var instance in activeInstances)
                {
                    instance.Status = WorkflowInstanceStatus.Terminated; // 已停止
                    instance.CompletedAt = DateTime.UtcNow;
                    instance.UpdatedAt = DateTime.UtcNow;
                    if (!string.IsNullOrEmpty(reason))
                    {
                        instance.Description += $" - 停止原因: {reason}";
                    }
                }

                await _workflowInstanceRepository.SaveChangesAsync();

                _logger.LogInformation("工作流停止成功: {Id}, 原因: {Reason}", id, reason);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "停止工作流失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 暂停工作流
        /// </summary>
        public async Task<bool> PauseWorkflowAsync(long id)
        {
            try
            {
                var runningInstances = await _workflowInstanceRepository.GetByWorkflowIdAsync(id);
                var activeInstances = runningInstances.Where(x => x.Status == WorkflowInstanceStatus.Running);

                foreach (var instance in activeInstances)
                {
                    instance.Status = WorkflowInstanceStatus.Paused; // 已暂停
                    instance.UpdatedAt = DateTime.UtcNow;
                }

                await _workflowInstanceRepository.SaveChangesAsync();

                _logger.LogInformation("工作流暂停成功: {Id}", id);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "暂停工作流失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 恢复工作流
        /// </summary>
        public async Task<bool> ResumeWorkflowAsync(long id)
        {
            try
            {
                var pausedInstances = await _workflowInstanceRepository.GetByWorkflowIdAsync(id);
                var pausedInstancesList = pausedInstances.Where(x => x.Status == WorkflowInstanceStatus.Paused);

                foreach (var instance in pausedInstancesList)
                {
                    instance.Status = WorkflowInstanceStatus.Running; // 运行中
                    instance.UpdatedAt = DateTime.UtcNow;
                }

                await _workflowInstanceRepository.SaveChangesAsync();

                _logger.LogInformation("工作流恢复成功: {Id}", id);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "恢复工作流失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 更新工作流状态
        /// </summary>
        public async Task<bool> UpdateStatusAsync(long id, byte status)
        {
            try
            {
                var workflow = await _workflowRepository.GetByIdAsync(id);
                if (workflow == null)
                {
                    return false;
                }

                workflow.Status = status;
                await _workflowRepository.SaveChangesAsync();

                _logger.LogInformation("更新工作流状态成功: {Id}, Status: {Status}", id, status);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新工作流状态失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 复制工作流
        /// </summary>
        public async Task<WorkflowDto> DuplicateAsync(long id, string newName, string newIdentifier)
        {
            try
            {
                var originalWorkflow = await _workflowRepository.GetByIdAsync(id);
                if (originalWorkflow == null)
                {
                    throw new ArgumentException($"工作流不存在: {id}");
                }

                // 检查新标识符是否重复
                if (!string.IsNullOrEmpty(newIdentifier))
                {
                    var exists = await IdentifierExistsAsync(newIdentifier);
                    if (exists)
                    {
                        throw new ArgumentException($"工作流标识符已存在: {newIdentifier}");
                    }
                }

                var newWorkflow = new Workflow
                {
                    Name = newName,
                    Steps = originalWorkflow.Steps,
                    Conditions = originalWorkflow.Conditions,
                    CreatedBy = 1, // 这里需要从上下文获取当前用户ID
                    CreatedAt = DateTime.UtcNow
                };

                await _workflowRepository.AddAsync(newWorkflow);
                await _workflowRepository.SaveChangesAsync();

                _logger.LogInformation("工作流复制成功: {OriginalId} -> {NewId}", id, newWorkflow.Id);
                return MapToDto(newWorkflow);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "复制工作流失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 复制工作流（接口兼容方法）
        /// </summary>
        public async Task<WorkflowDto?> CopyWorkflowAsync(long id, string newName)
        {
            var newIdentifier = $"{newName}_{DateTime.Now:yyyyMMddHHmmss}";
            return await DuplicateAsync(id, newName, newIdentifier);
        }

        /// <summary>
        /// 验证工作流
        /// </summary>
    public Task<(bool IsValid, List<string> Errors)> ValidateWorkflowAsync(WorkflowDto workflowDto)
        {
            try
            {
                var errors = new List<string>();

                // 基本验证
                if (string.IsNullOrWhiteSpace(workflowDto.Name))
                {
                    errors.Add("工作流名称不能为空");
                }

                if (string.IsNullOrWhiteSpace(workflowDto.Definition))
                {
                    errors.Add("工作流定义不能为空");
                }
                else
                {
                    // 验证JSON格式
                    try
                    {
                        JsonDocument.Parse(workflowDto.Definition);
                    }
                    catch
                    {
                        errors.Add("工作流定义JSON格式无效");
                    }
                }

                // 验证条件JSON格式
                if (!string.IsNullOrEmpty(workflowDto.Conditions))
                {
                    try
                    {
                        JsonDocument.Parse(workflowDto.Conditions);
                    }
                    catch
                    {
                        errors.Add("条件配置JSON格式无效");
                    }
                }

                return Task.FromResult((errors.Count == 0, errors));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证工作流失败");
                return Task.FromResult((false, new List<string> { "验证过程中发生错误" }));
            }
        }

        /// <summary>
        /// 检查标识符是否存在
        /// </summary>
        public async Task<bool> IdentifierExistsAsync(string identifier, long? excludeId = null)
        {
            try
            {
                return await _workflowRepository.IsCodeExistsAsync(identifier, excludeId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查工作流标识符存在性失败: {Identifier}", identifier);
                throw;
            }
        }

        /// <summary>
        /// 获取工作流实例
        /// </summary>
        public async Task<(IEnumerable<object> Items, int TotalCount)> GetWorkflowInstancesAsync(long id, string? status = null, int pageIndex = 1, int pageSize = 20)
        {
            try
            {
                var instances = await _workflowInstanceRepository.GetByWorkflowIdAsync(id);

                // 状态过滤
                if (!string.IsNullOrEmpty(status) && int.TryParse(status, out int statusInt))
                {
                    var statusEnum = (WorkflowInstanceStatus)statusInt;
                    instances = instances.Where(x => x.Status == statusEnum).ToList();
                }

                var totalCount = instances.Count();
                var items = instances
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .Select(x => new
                    {
                        x.Id,
                        x.InstanceName,
                        Status = x.Status.ToString(),
                        x.CurrentNode,
                        StartTime = x.CreatedAt,
                        EndTime = x.CompletedAt,
                        InitiatorName = "系统用户", // 这里应该关联用户信息
                        x.Description
                    })
                    .ToList();

                return (items, totalCount);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流实例失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 获取执行历史
        /// </summary>
        public async Task<(IEnumerable<object> Items, int TotalCount)> GetExecutionHistoryAsync(long id, int pageIndex = 1, int pageSize = 20)
        {
            try
            {
                var instances = await _workflowInstanceRepository.GetByWorkflowIdAsync(id);
                var completedInstances = instances.Where(x => x.Status == WorkflowInstanceStatus.Completed || x.Status == WorkflowInstanceStatus.Failed); // 已完成或失败

                var totalCount = completedInstances.Count();
                var items = completedInstances
                    .OrderByDescending(x => x.CompletedAt)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .Select(x => new
                    {
                        x.Id,
                        x.InstanceName,
                        Status = x.Status.ToString(),
                        StartTime = x.CreatedAt,
                        EndTime = x.CompletedAt,
                        Duration = x.CompletedAt.HasValue ? (x.CompletedAt.Value - x.CreatedAt).ToString(@"hh\:mm\:ss") : null,
                        InitiatorName = "系统用户",
                        x.Description
                    })
                    .ToList();

                return (items, totalCount);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流执行历史失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 获取工作流统计信息
        /// </summary>
        public async Task<object> GetWorkflowStatisticsAsync(long id, string period = "month")
        {
            try
            {
                var instances = await _workflowInstanceRepository.GetByWorkflowIdAsync(id);
                var (startDate, endDate) = GetPeriodRange(period);
                
                // 按时间段筛选
                var filteredInstances = instances.Where(x => x.CreatedAt >= startDate && x.CreatedAt <= endDate).ToList();
                var allInstances = instances.ToList();

                var totalInstances = allInstances.Count;
                var periodInstances = filteredInstances.Count;
                var runningInstances = allInstances.Count(x => x.Status == WorkflowInstanceStatus.Running);
                var pausedInstances = allInstances.Count(x => x.Status == WorkflowInstanceStatus.Paused);
                var completedInstances = allInstances.Count(x => x.Status == WorkflowInstanceStatus.Completed);
                var failedInstances = allInstances.Count(x => x.Status == WorkflowInstanceStatus.Failed);

                var completedInPeriod = filteredInstances.Count(x => x.Status == WorkflowInstanceStatus.Completed);
                var failedInPeriod = filteredInstances.Count(x => x.Status == WorkflowInstanceStatus.Failed);

                return new
                {
                    Period = period,
                    PeriodRange = new { Start = startDate, End = endDate },
                    Summary = new
                    {
                        TotalInstances = totalInstances,
                        PeriodInstances = periodInstances,
                        RunningInstances = runningInstances,
                        PausedInstances = pausedInstances,
                        CompletedInstances = completedInstances,
                        FailedInstances = failedInstances
                    },
                    PeriodMetrics = new
                    {
                        CompletedInPeriod = completedInPeriod,
                        FailedInPeriod = failedInPeriod,
                        SuccessRate = periodInstances > 0 ? Math.Round((double)completedInPeriod / (completedInPeriod + failedInPeriod) * 100, 2) : 0,
                        AverageExecutionTime = GetAverageExecutionTime(filteredInstances.Where(x => x.CompletedAt.HasValue))
                    },
                    Distribution = new
                    {
                        ByStatus = new[]
                        {
                            new { Status = "Running", Count = runningInstances, Percentage = totalInstances > 0 ? Math.Round((double)runningInstances / totalInstances * 100, 2) : 0 },
                            new { Status = "Paused", Count = pausedInstances, Percentage = totalInstances > 0 ? Math.Round((double)pausedInstances / totalInstances * 100, 2) : 0 },
                            new { Status = "Completed", Count = completedInstances, Percentage = totalInstances > 0 ? Math.Round((double)completedInstances / totalInstances * 100, 2) : 0 },
                            new { Status = "Failed", Count = failedInstances, Percentage = totalInstances > 0 ? Math.Round((double)failedInstances / totalInstances * 100, 2) : 0 }
                        }
                    }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流统计信息失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 获取全局统计信息
        /// </summary>
        public async Task<object> GetGlobalStatisticsAsync(string period = "month")
        {
            try
            {
                var workflows = await _workflowRepository.GetAllAsync();
                var instances = await _workflowInstanceRepository.GetAllAsync();
                var tasks = await _workflowTaskRepository.GetAllAsync();

                var (startDate, endDate) = GetPeriodRange(period);
                var periodInstances = instances.Where(x => x.CreatedAt >= startDate && x.CreatedAt <= endDate).ToList();
                var periodTasks = tasks.Where(x => x.CreatedAt >= startDate && x.CreatedAt <= endDate).ToList();

                return new
                {
                    Period = period,
                    PeriodRange = new { Start = startDate, End = endDate },
                    Overview = new
                    {
                        TotalWorkflows = workflows.Count(),
                        ActiveWorkflows = workflows.Count(), // 简化实现
                        TotalInstances = instances.Count(),
                        PeriodInstances = periodInstances.Count,
                        TotalTasks = tasks.Count(),
                        PeriodTasks = periodTasks.Count
                    },
                    InstanceMetrics = new
                    {
                        Running = instances.Count(x => x.Status == WorkflowInstanceStatus.Running),
                        Paused = instances.Count(x => x.Status == WorkflowInstanceStatus.Paused),
                        Completed = instances.Count(x => x.Status == WorkflowInstanceStatus.Completed),
                        Failed = instances.Count(x => x.Status == WorkflowInstanceStatus.Failed),
                        CompletedToday = instances.Count(x => x.CompletedAt.HasValue && x.CompletedAt.Value.Date == DateTime.Today),
                        CompletedInPeriod = periodInstances.Count(x => x.Status == WorkflowInstanceStatus.Completed)
                    },
                    TaskMetrics = new
                    {
                        Pending = tasks.Count(x => x.Status == WorkflowTaskStatus.Pending),
                        InProgress = tasks.Count(x => x.Status == WorkflowTaskStatus.InProgress),
                        Completed = tasks.Count(x => x.Status == WorkflowTaskStatus.Completed),
                        Overdue = tasks.Count(x => x.DueDate.HasValue && x.DueDate.Value < DateTime.UtcNow && 
                                               (x.Status == WorkflowTaskStatus.Pending || x.Status == WorkflowTaskStatus.InProgress))
                    },
                    Performance = new
                    {
                        AverageExecutionTime = GetAverageExecutionTime(instances.Where(x => x.CompletedAt.HasValue)),
                        SuccessRate = instances.Count() > 0 ? 
                            Math.Round((double)instances.Count(x => x.Status == WorkflowInstanceStatus.Completed) / instances.Count() * 100, 2) : 0
                    }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取全局统计信息失败");
                throw;
            }
        }

        /// <summary>
        /// 获取工作流性能统计
        /// </summary>
        public async Task<object> GetWorkflowPerformanceStatisticsAsync(long id, string period = "month")
        {
            try
            {
                var instances = await _workflowInstanceRepository.GetByWorkflowIdAsync(id);
                var (startDate, endDate) = GetPeriodRange(period);
                
                var filteredInstances = instances.Where(x => x.CreatedAt >= startDate && x.CreatedAt <= endDate).ToList();
                var completedInstances = filteredInstances.Where(x => x.CompletedAt.HasValue).ToList();

                var executionTimes = completedInstances
                    .Select(x => (x.CompletedAt!.Value - x.CreatedAt).TotalMinutes)
                    .OrderBy(x => x)
                    .ToList();

                return new
                {
                    Period = period,
                    TotalInstances = filteredInstances.Count,
                    CompletedInstances = completedInstances.Count,
                    ExecutionTime = new
                    {
                        Average = executionTimes.Any() ? Math.Round(executionTimes.Average(), 2) : 0,
                        Median = executionTimes.Any() ? Math.Round(GetMedian(executionTimes), 2) : 0,
                        Min = executionTimes.Any() ? Math.Round(executionTimes.Min(), 2) : 0,
                        Max = executionTimes.Any() ? Math.Round(executionTimes.Max(), 2) : 0,
                        P50 = executionTimes.Any() ? Math.Round(GetPercentile(executionTimes, 50), 2) : 0,
                        P90 = executionTimes.Any() ? Math.Round(GetPercentile(executionTimes, 90), 2) : 0,
                        P95 = executionTimes.Any() ? Math.Round(GetPercentile(executionTimes, 95), 2) : 0,
                        P99 = executionTimes.Any() ? Math.Round(GetPercentile(executionTimes, 99), 2) : 0
                    },
                    Throughput = new
                    {
                        InstancesPerDay = GetThroughputData(filteredInstances, "day"),
                        InstancesPerHour = GetThroughputData(filteredInstances, "hour")
                    }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流性能统计信息失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 获取工作流趋势统计
        /// </summary>
        public async Task<object> GetWorkflowTrendStatisticsAsync(long id, int days = 30)
        {
            try
            {
                var instances = await _workflowInstanceRepository.GetByWorkflowIdAsync(id);
                var startDate = DateTime.UtcNow.Date.AddDays(-days);
                var endDate = DateTime.UtcNow.Date.AddDays(1);

                var filteredInstances = instances.Where(x => x.CreatedAt >= startDate && x.CreatedAt < endDate).ToList();

                var trendData = new List<object>();
                for (var date = startDate; date < endDate; date = date.AddDays(1))
                {
                    var dayInstances = filteredInstances.Where(x => x.CreatedAt.Date == date).ToList();
                    trendData.Add(new
                    {
                        Date = date.ToString("yyyy-MM-dd"),
                        Total = dayInstances.Count,
                        Completed = dayInstances.Count(x => x.Status == WorkflowInstanceStatus.Completed),
                        Failed = dayInstances.Count(x => x.Status == WorkflowInstanceStatus.Failed),
                        Running = dayInstances.Count(x => x.Status == WorkflowInstanceStatus.Running),
                        SuccessRate = dayInstances.Count > 0 ? 
                            Math.Round((double)dayInstances.Count(x => x.Status == WorkflowInstanceStatus.Completed) / dayInstances.Count * 100, 2) : 0
                    });
                }

                return new
                {
                    Days = days,
                    StartDate = startDate,
                    EndDate = endDate,
                    TrendData = trendData,
                    Summary = new
                    {
                        TotalInstances = filteredInstances.Count,
                        AveragePerDay = Math.Round((double)filteredInstances.Count / days, 2),
                        PeakDay = trendData.Cast<dynamic>().OrderByDescending(x => x.Total).FirstOrDefault()?.Date,
                        BestSuccessRateDay = trendData.Cast<dynamic>().OrderByDescending(x => x.SuccessRate).FirstOrDefault()?.Date
                    }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流趋势统计信息失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 导出工作流
        /// </summary>
        public async Task<string?> ExportWorkflowAsync(long id, string format = "json")
        {
            try
            {
                var workflow = await _workflowRepository.GetByIdAsync(id);
                if (workflow == null)
                {
                    return null;
                }

                var workflowDto = MapToDto(workflow);
                
                switch (format.ToLower())
                {
                    case "json":
                        return JsonSerializer.Serialize(workflowDto, new JsonSerializerOptions 
                        { 
                            WriteIndented = true,
                            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                        });
                    
                    case "xml":
                        return SerializeToXml(workflowDto);
                    
                    case "yaml":
                        return SerializeToYaml(workflowDto);
                    
                    default:
                        throw new NotSupportedException($"不支持的导出格式: {format}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出工作流失败: {Id}", id);
                throw;
            }
        }

        /// <summary>
        /// 批量导出工作流为ZIP文件
        /// </summary>
        public async Task<byte[]> ExportWorkflowsAsZipAsync(long[] ids, string format = "json")
        {
            try
            {
                using var memoryStream = new MemoryStream();
                using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    foreach (var id in ids)
                    {
                        var workflowData = await ExportWorkflowAsync(id, format);
                        if (workflowData != null)
                        {
                            var workflow = await _workflowRepository.GetByIdAsync(id);
                            var fileName = $"{SanitizeFileName(workflow?.Name ?? $"workflow_{id}")}.{GetFileExtension(format)}";
                            
                            var entry = archive.CreateEntry(fileName);
                            using var entryStream = entry.Open();
                            using var writer = new StreamWriter(entryStream);
                            await writer.WriteAsync(workflowData);
                        }
                    }
                }

                return memoryStream.ToArray();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量导出工作流失败");
                throw;
            }
        }

        /// <summary>
        /// 导入工作流
        /// </summary>
        public async Task<WorkflowDto?> ImportWorkflowAsync(string jsonData, bool overwrite = false)
        {
            try
            {
                var workflowDto = JsonSerializer.Deserialize<WorkflowDto>(jsonData);

                if (workflowDto == null)
                {
                    throw new InvalidOperationException("无法解析工作流数据");
                }

                // 检查是否存在
                var existing = await GetByIdentifierAsync(workflowDto.Identifier);
                if (existing != null && !overwrite)
                {
                    throw new InvalidOperationException($"工作流已存在: {workflowDto.Identifier}");
                }

                if (existing != null && overwrite)
                {
                    // 更新现有工作流
                    workflowDto.Id = existing.Id;
                    return await UpdateAsync(workflowDto);
                }
                else
                {
                    // 创建新工作流
                    workflowDto.Id = 0;
                    return await CreateAsync(workflowDto);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导入工作流失败");
                throw;
            }
        }

        /// <summary>
        /// 从ZIP文件批量导入工作流
        /// </summary>
        public async Task<WorkflowBatchImportResult> ImportWorkflowsFromZipAsync(byte[] zipData, bool overwrite = false)
        {
            var result = new WorkflowBatchImportResult();

            try
            {
                using var stream = new MemoryStream(zipData);
                using var archive = new ZipArchive(stream, ZipArchiveMode.Read);

                foreach (var entry in archive.Entries)
                {
                    if (!entry.FullName.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
                        continue;

                    try
                    {
                        using var entryStream = entry.Open();
                        using var reader = new StreamReader(entryStream);
                        var jsonContent = await reader.ReadToEndAsync();

                        var importedWorkflow = await ImportWorkflowAsync(jsonContent, overwrite);
                        if (importedWorkflow != null)
                        {
                            result.SuccessWorkflows.Add(importedWorkflow);
                            result.SuccessCount++;
                        }
                    }
                    catch (Exception ex)
                    {
                        result.FailedImports.Add(new WorkflowImportFailure
                        {
                            FileName = entry.FullName,
                            ErrorMessage = ex.Message
                        });
                        result.FailCount++;
                        _logger.LogWarning(ex, "导入工作流文件失败: {FileName}", entry.FullName);
                    }
                }

                _logger.LogInformation("批量导入工作流完成，成功: {SuccessCount}，失败: {FailCount}", 
                    result.SuccessCount, result.FailCount);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量导入工作流失败");
                throw;
            }
        }

        /// <summary>
        /// 清理过期实例
        /// </summary>
        public async Task<int> CleanupExpiredInstancesAsync(int daysToKeep = 30)
        {
            try
            {
                var cutoffDate = DateTime.UtcNow.AddDays(-daysToKeep);
                var expiredInstances = await _workflowInstanceRepository.FindAsync(x => 
                    x.CompletedAt.HasValue && x.CompletedAt < cutoffDate);

                int deletedCount = 0;
                foreach (var instance in expiredInstances)
                {
                    await _workflowInstanceRepository.DeleteAsync(instance);
                    deletedCount++;
                }

                if (deletedCount > 0)
                {
                    await _workflowInstanceRepository.SaveChangesAsync();
                }

                _logger.LogInformation("清理过期工作流实例完成，删除数量: {Count}", deletedCount);
                return deletedCount;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理过期工作流实例失败");
                throw;
            }
        }

        #region Private Methods

        /// <summary>
        /// 将实体映射为DTO
        /// </summary>
        private static WorkflowDto MapToDto(Workflow workflow)
        {
            return new WorkflowDto
            {
                Id = workflow.Id,
                Name = workflow.Name,
                Identifier = workflow.Id.ToString(), // 简化实现
                Definition = workflow.Steps,
                Conditions = workflow.Conditions,
                CreatedAt = workflow.CreatedAt,
                CreatedBy = workflow.CreatedBy
            };
        }

        /// <summary>
        /// 获取状态名称
        /// </summary>
        private static string GetStatusName(int status)
        {
            return status switch
            {
                1 => "运行中",
                2 => "已暂停", 
                3 => "已完成",
                4 => "已失败",
                _ => "未知"
            };
        }

        /// <summary>
        /// 序列化为XML
        /// </summary>
        private static string SerializeToXml(WorkflowDto workflow)
        {
            // 简化的XML序列化实现
            var xml = $@"<?xml version=""1.0"" encoding=""UTF-8""?>
<Workflow>
    <Id>{workflow.Id}</Id>
    <Name>{System.Security.SecurityElement.Escape(workflow.Name)}</Name>
    <Identifier>{System.Security.SecurityElement.Escape(workflow.Identifier)}</Identifier>
    <Definition>{System.Security.SecurityElement.Escape(workflow.Definition ?? "")}</Definition>
    <Conditions>{System.Security.SecurityElement.Escape(workflow.Conditions ?? "")}</Conditions>
    <CreatedAt>{workflow.CreatedAt:O}</CreatedAt>
    <CreatedBy>{workflow.CreatedBy}</CreatedBy>
</Workflow>";
            return xml;
        }

        /// <summary>
        /// 序列化为YAML
        /// </summary>
        private static string SerializeToYaml(WorkflowDto workflow)
        {
            // 简化的YAML序列化实现
            var yaml = $@"id: {workflow.Id}
name: ""{workflow.Name?.Replace("\"", "\\\"")}""
identifier: ""{workflow.Identifier?.Replace("\"", "\\\"")}""
definition: |
{(string.IsNullOrEmpty(workflow.Definition) ? "  null" : "  " + workflow.Definition.Replace("\n", "\n  "))}
conditions: |
{(string.IsNullOrEmpty(workflow.Conditions) ? "  null" : "  " + workflow.Conditions.Replace("\n", "\n  "))}
createdAt: ""{workflow.CreatedAt:O}""
createdBy: {workflow.CreatedBy}";
            return yaml;
        }

        /// <summary>
        /// 清理文件名中的非法字符
        /// </summary>
        private static string SanitizeFileName(string fileName)
        {
            var invalidChars = Path.GetInvalidFileNameChars();
            foreach (var invalidChar in invalidChars)
            {
                fileName = fileName.Replace(invalidChar, '_');
            }
            return fileName;
        }

        /// <summary>
        /// 获取文件扩展名
        /// </summary>
        private static string GetFileExtension(string format)
        {
            return format.ToLower() switch
            {
                "xml" => "xml",
                "yaml" => "yaml",
                _ => "json"
            };
        }

        /// <summary>
        /// 获取时间段范围
        /// </summary>
        private static (DateTime StartDate, DateTime EndDate) GetPeriodRange(string period)
        {
            var now = DateTime.UtcNow;
            return period.ToLower() switch
            {
                "today" => (now.Date, now.Date.AddDays(1)),
                "week" => (now.Date.AddDays(-(int)now.DayOfWeek), now.Date.AddDays(7 - (int)now.DayOfWeek)),
                "month" => (new DateTime(now.Year, now.Month, 1), new DateTime(now.Year, now.Month, 1).AddMonths(1)),
                "quarter" => GetQuarterRange(now),
                "year" => (new DateTime(now.Year, 1, 1), new DateTime(now.Year + 1, 1, 1)),
                _ => (now.Date.AddDays(-30), now.Date.AddDays(1)) // 默认30天
            };
        }

        /// <summary>
        /// 获取季度范围
        /// </summary>
        private static (DateTime StartDate, DateTime EndDate) GetQuarterRange(DateTime date)
        {
            var quarter = (date.Month - 1) / 3 + 1;
            var startMonth = (quarter - 1) * 3 + 1;
            var startDate = new DateTime(date.Year, startMonth, 1);
            var endDate = startDate.AddMonths(3);
            return (startDate, endDate);
        }

        /// <summary>
        /// 计算平均执行时间（分钟）
        /// </summary>
        private static double GetAverageExecutionTime(IEnumerable<WorkflowInstance> instances)
        {
            var times = instances.Where(x => x.CompletedAt.HasValue)
                                 .Select(x => (x.CompletedAt!.Value - x.CreatedAt).TotalMinutes)
                                 .ToList();
            return times.Any() ? Math.Round(times.Average(), 2) : 0;
        }

        /// <summary>
        /// 获取中位数
        /// </summary>
        private static double GetMedian(List<double> values)
        {
            if (!values.Any()) return 0;
            var sortedValues = values.OrderBy(x => x).ToList();
            var count = sortedValues.Count;
            if (count % 2 == 0)
            {
                return (sortedValues[count / 2 - 1] + sortedValues[count / 2]) / 2.0;
            }
            return sortedValues[count / 2];
        }

        /// <summary>
        /// 获取百分位数
        /// </summary>
        private static double GetPercentile(List<double> values, double percentile)
        {
            if (!values.Any()) return 0;
            var sortedValues = values.OrderBy(x => x).ToList();
            var index = (percentile / 100.0) * (sortedValues.Count - 1);
            var lower = (int)Math.Floor(index);
            var upper = (int)Math.Ceiling(index);
            
            if (lower == upper) return sortedValues[lower];
            
            var weight = index - lower;
            return sortedValues[lower] * (1 - weight) + sortedValues[upper] * weight;
        }

        /// <summary>
        /// 获取吞吐量数据
        /// </summary>
        private static object GetThroughputData(List<WorkflowInstance> instances, string unit)
        {
            if (!instances.Any()) return new { Average = 0, Peak = 0, Current = 0 };

            IEnumerable<int> countsEnum = unit.ToLower() switch
            {
                "hour" => instances
                    .GroupBy(x => new { x.CreatedAt.Date, x.CreatedAt.Hour })
                    .Select(g => g.Count()),
                "day" => instances
                    .GroupBy(x => x.CreatedAt.Date)
                    .Select(g => g.Count()),
                _ => instances
                    .GroupBy(x => x.CreatedAt.Date)
                    .Select(g => g.Count())
            };

            var counts = countsEnum.ToList();
            return new
            {
                Average = counts.Any() ? Math.Round(counts.Average(), 2) : 0,
                Peak = counts.Any() ? counts.Max() : 0,
                Current = counts.LastOrDefault()
            };
        }

        #endregion

        #region Task Lifecycle

        /// <summary>
        /// 将任务置为进行中
        /// </summary>
        public async Task<bool> StartTaskAsync(long taskId, long userId, string? comment = null)
        {
            var task = await _workflowTaskRepository.GetByIdAsync(taskId);
            if (task == null) return false;
            if (task.AssigneeId != userId)
            {
                _logger.LogWarning("用户{UserId}无权开始任务{TaskId}", userId, taskId);
                return false;
            }

            if (task.Status == WorkflowTaskStatus.Completed || task.Status == WorkflowTaskStatus.Rejected)
            {
                return true;
            }

            task.Status = WorkflowTaskStatus.InProgress;
            task.UpdatedAt = DateTime.UtcNow;
            task.Comments = AppendComment(task.Comments, comment, userId, "start");
            await _workflowTaskRepository.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 完成任务并尝试推进到下一节点
        /// </summary>
        public async Task<bool> CompleteTaskAsync(long taskId, long userId, string? comment = null, Dictionary<string, object>? outputData = null)
        {
            var task = await _workflowTaskRepository.GetByIdAsync(taskId);
            if (task == null) return false;
            if (task.AssigneeId != userId)
            {
                _logger.LogWarning("用户{UserId}无权完成任务{TaskId}", userId, taskId);
                return false;
            }

            task.Status = WorkflowTaskStatus.Completed;
            task.UpdatedAt = DateTime.UtcNow;
            task.CompletedAt = DateTime.UtcNow;
            task.Comments = AppendComment(task.Comments, comment, userId, "complete");

            // 合并输出到实例上下文
            var instance = await _workflowInstanceRepository.GetByIdAsync(task.InstanceId);
            if (instance == null) return false;
            if (outputData != null && outputData.Count > 0)
            {
                try
                {
                    var ctx = string.IsNullOrWhiteSpace(instance.ContextData) ?
                        new Dictionary<string, object>() :
                        JsonSerializer.Deserialize<Dictionary<string, object>>(instance.ContextData!) ?? new();
                    foreach (var kv in outputData) ctx[kv.Key] = kv.Value;
                    instance.ContextData = JsonSerializer.Serialize(ctx);
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, "合并任务输出到实例上下文失败：{InstanceId}", instance.Id);
                }
            }

            // 会签/并行任务：仅当同节点剩余无待处理或进行中任务时才推进
            var remaining = await _workflowTaskRepository.FindAsync(x =>
                x.InstanceId == instance.Id && x.NodeName == task.NodeName &&
                (x.Status == WorkflowTaskStatus.Pending || x.Status == WorkflowTaskStatus.InProgress));

            var advanced = true;
            if (!remaining.Any())
            {
                // 基于定义推进
                advanced = await AdvanceInstanceInternalAsync(instance, task.NodeName);
            }

            await _workflowTaskRepository.SaveChangesAsync();
            await _workflowInstanceRepository.SaveChangesAsync();
            return advanced;
        }

        /// <summary>
        /// 拒绝任务 -> 实例失败
        /// </summary>
        public async Task<bool> RejectTaskAsync(long taskId, long userId, string? reason = null)
        {
            var task = await _workflowTaskRepository.GetByIdAsync(taskId);
            if (task == null) return false;
            if (task.AssigneeId != userId)
            {
                _logger.LogWarning("用户{UserId}无权拒绝任务{TaskId}", userId, taskId);
                return false;
            }

            task.Status = WorkflowTaskStatus.Rejected;
            task.UpdatedAt = DateTime.UtcNow;
            task.Comments = AppendComment(task.Comments, reason, userId, "reject");

            var instance = await _workflowInstanceRepository.GetByIdAsync(task.InstanceId);
            if (instance != null)
            {
                instance.Status = WorkflowInstanceStatus.Failed;
                instance.CompletedAt = DateTime.UtcNow;
                instance.UpdatedAt = DateTime.UtcNow;
            }

            await _workflowTaskRepository.SaveChangesAsync();
            await _workflowInstanceRepository.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 主动推进实例（用于自动节点）
        /// </summary>
        public async Task<bool> AdvanceInstanceAsync(long instanceId)
        {
            var instance = await _workflowInstanceRepository.GetByIdAsync(instanceId);
            if (instance == null) return false;
            var advanced = await AdvanceInstanceInternalAsync(instance, instance.CurrentNode);
            await _workflowInstanceRepository.SaveChangesAsync();
            return advanced;
        }

        private async Task<bool> AdvanceInstanceInternalAsync(WorkflowInstance instance, string? fromNode)
        {
            // 解析流程定义
            var def = TryParseDefinition(instance.Workflow?.Steps);

            // 若无定义，则退化为默认逻辑：Start -> Approval -> End
            if (def == null)
            {
                if (string.IsNullOrWhiteSpace(instance.CurrentNode) || instance.CurrentNode == "StartNode")
                {
                    await CreateUserTasksForNode(instance, new NodeDef { Id = "Approval", Name = "审批", Type = "userTask", CandidateUserIds = new List<long> { instance.InitiatorId }, SlaHours = 72 });
                    instance.CurrentNode = "Approval";
                    instance.Status = WorkflowInstanceStatus.Running;
                    instance.UpdatedAt = DateTime.UtcNow;
                    return true;
                }
                if (fromNode == "Approval")
                {
                    instance.CurrentNode = "End";
                    instance.Status = WorkflowInstanceStatus.Completed;
                    instance.CompletedAt = DateTime.UtcNow;
                    instance.UpdatedAt = DateTime.UtcNow;
                    return true;
                }
                return false;
            }

            var ctx = ParseContext(instance.ContextData);

            // 起点推进：如果还未进入任何节点
            var currentNodeId = ResolveNodeIdByNameOrId(def, string.IsNullOrWhiteSpace(instance.CurrentNode) ? fromNode : instance.CurrentNode);
            if (string.IsNullOrWhiteSpace(currentNodeId))
            {
                var start = def.Nodes.FirstOrDefault(n => string.Equals(n.Type, "start", StringComparison.OrdinalIgnoreCase));
                if (start == null)
                {
                    _logger.LogWarning("流程定义缺少起始节点，实例{InstanceId}", instance.Id);
                    return false;
                }
                currentNodeId = start.Id;
            }

            // 选择所有满足条件的后继边
            var nextEdges = def.Edges.Where(e => string.Equals(e.From, currentNodeId, StringComparison.OrdinalIgnoreCase))
                                     .Where(e => EvaluateCondition(ctx, e.Condition))
                                     .ToList();

            if (!nextEdges.Any())
            {
                _logger.LogInformation("当前节点无后继或条件不满足，等待外部事件，实例{InstanceId} 节点{Node}", instance.Id, currentNodeId);
                return false;
            }

            // 针对每条边的目标节点进行处理
            var progressed = false;
            foreach (var edge in nextEdges)
            {
                var target = def.Nodes.FirstOrDefault(n => string.Equals(n.Id, edge.To, StringComparison.OrdinalIgnoreCase));
                if (target == null) continue;

                if (target.Type.Equals("userTask", StringComparison.OrdinalIgnoreCase))
                {
                    await CreateUserTasksForNode(instance, target);
                    instance.CurrentNode = target.Name ?? target.Id;
                    instance.Status = WorkflowInstanceStatus.Running;
                    instance.UpdatedAt = DateTime.UtcNow;
                    progressed = true;
                }
                else if (target.Type.Equals("auto", StringComparison.OrdinalIgnoreCase))
                {
                    instance.CurrentNode = target.Name ?? target.Id;
                    instance.Status = WorkflowInstanceStatus.Running;
                    instance.UpdatedAt = DateTime.UtcNow;
                    // 自动节点直接继续推进（防止死循环，最多推进10步）
                    for (int i = 0; i < 10; i++)
                    {
                        var cont = await AdvanceInstanceInternalAsync(instance, target.Id);
                        if (!cont) break;
                        progressed = true;
                    }
                }
                else if (target.Type.Equals("end", StringComparison.OrdinalIgnoreCase))
                {
                    instance.CurrentNode = target.Name ?? target.Id;
                    instance.Status = WorkflowInstanceStatus.Completed;
                    instance.CompletedAt = DateTime.UtcNow;
                    instance.UpdatedAt = DateTime.UtcNow;
                    progressed = true;
                }
            }
            return progressed;
        }

        private static string AppendComment(string? existing, string? addition, long userId, string action)
        {
            if (string.IsNullOrWhiteSpace(addition)) return existing ?? string.Empty;
            var line = $"[{DateTime.UtcNow:O}] user:{userId} {action}: {addition}";
            return string.IsNullOrWhiteSpace(existing) ? line : existing + "\n" + line;
        }

        #endregion

        #region Definition Routing Helpers

        private sealed class WorkflowDef
        {
            public List<NodeDef> Nodes { get; set; } = new();
            public List<EdgeDef> Edges { get; set; } = new();
        }

        private sealed class NodeDef
        {
            public string Id { get; set; } = string.Empty;
            public string? Name { get; set; }
            public string Type { get; set; } = "userTask"; // start/userTask/auto/end
            public List<long>? CandidateUserIds { get; set; }
            public List<string>? RoleCodes { get; set; }
            public int? SlaHours { get; set; }
        }

        private sealed class EdgeDef
        {
            public string From { get; set; } = string.Empty;
            public string To { get; set; } = string.Empty;
            public ConditionDef? Condition { get; set; }
        }

        private sealed class ConditionDef
        {
            public string? Key { get; set; }
            public string? Op { get; set; } // ==, !=, >, < (仅对数字支持)
            public JsonElement? Value { get; set; }
        }

        private WorkflowDef? TryParseDefinition(string? json)
        {
            if (string.IsNullOrWhiteSpace(json)) return null;
            try
            {
                return JsonSerializer.Deserialize<WorkflowDef>(json);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "解析流程定义失败，使用默认流程");
                return null;
            }
        }

        private static Dictionary<string, object> ParseContext(string? json)
        {
            if (string.IsNullOrWhiteSpace(json)) return new();
            try
            {
                var dict = JsonSerializer.Deserialize<Dictionary<string, object>>(json);
                return dict ?? new();
            }
            catch
            {
                return new();
            }
        }

        private static bool EvaluateCondition(Dictionary<string, object> ctx, ConditionDef? cond)
        {
            if (cond == null || string.IsNullOrWhiteSpace(cond.Key)) return true;
            if (!ctx.TryGetValue(cond.Key, out var actual)) return false;

            object? expected = null;
            if (cond.Value.HasValue)
            {
                var v = cond.Value.Value;
                expected = v.ValueKind switch
                {
                    JsonValueKind.True => true,
                    JsonValueKind.False => false,
                    JsonValueKind.Number => v.TryGetInt64(out var i) ? (object)i : v.TryGetDouble(out var d) ? d : v.ToString(),
                    JsonValueKind.String => v.GetString(),
                    _ => v.ToString()
                };
            }

            var op = (cond.Op ?? "==").Trim();
            try
            {
                // 简化比较：尝试转数字/布尔，再到字符串
                if (op == "==") return Normalize(actual)?.Equals(Normalize(expected)) == true;
                if (op == "!=") return Normalize(actual)?.Equals(Normalize(expected)) != true;
                if (op == ">" || op == "<")
                {
                    var a = ToDouble(Normalize(actual));
                    var b = ToDouble(Normalize(expected));
                    if (a == null || b == null) return false;
                    return op == ">" ? a > b : a < b;
                }
            }
            catch { }
            return false;
        }

        private static object? Normalize(object? o)
        {
            if (o is JsonElement je)
            {
                return je.ValueKind switch
                {
                    JsonValueKind.True => true,
                    JsonValueKind.False => false,
                    JsonValueKind.Number => je.TryGetInt64(out var i) ? (object)i : je.TryGetDouble(out var d) ? d : je.ToString(),
                    JsonValueKind.String => je.GetString(),
                    _ => je.ToString()
                };
            }
            return o;
        }

        private static double? ToDouble(object? o)
        {
            if (o is null) return null;
            if (o is double dd) return dd;
            if (o is float ff) return ff;
            if (o is long ll) return ll;
            if (o is int ii) return ii;
            if (double.TryParse(o.ToString(), out var d)) return d;
            return null;
        }

        private static string? ResolveNodeIdByNameOrId(WorkflowDef def, string? nameOrId)
        {
            if (string.IsNullOrWhiteSpace(nameOrId)) return null;
            var byId = def.Nodes.FirstOrDefault(n => string.Equals(n.Id, nameOrId, StringComparison.OrdinalIgnoreCase));
            if (byId != null) return byId.Id;
            var byName = def.Nodes.FirstOrDefault(n => string.Equals(n.Name, nameOrId, StringComparison.OrdinalIgnoreCase));
            return byName?.Id;
        }

        private async Task CreateUserTasksForNode(WorkflowInstance instance, NodeDef node)
        {
            var assignees = (node.CandidateUserIds != null && node.CandidateUserIds.Any())
                ? node.CandidateUserIds
                : new List<long> { instance.InitiatorId };

            var due = node.SlaHours.HasValue ? DateTime.UtcNow.AddHours(node.SlaHours.Value) : (DateTime?)null;
            foreach (var uid in assignees)
            {
                var newTask = new WorkflowTask
                {
                    InstanceId = instance.Id,
                    TaskName = node.Name ?? node.Id,
                    NodeName = node.Name ?? node.Id,
                    AssigneeId = uid,
                    Status = WorkflowTaskStatus.Pending,
                    CreatedAt = DateTime.UtcNow,
                    DueDate = due
                };
                await _workflowTaskRepository.AddAsync(newTask);
            }
            await _workflowTaskRepository.SaveChangesAsync();
        }

        #endregion

        #region Queries: My Tasks & Instances, Overdue refresh

        /// <summary>
        /// 我的待办任务（含处理中）
        /// </summary>
        public async Task<(IEnumerable<object> Items, int TotalCount)> GetMyPendingTasksAsync(long userId, int pageIndex = 1, int pageSize = 20, int? priority = null, DateTime? dueBefore = null, string? keyword = null)
        {
            // 基于仓储筛选后做内存过滤（若性能压力可下推至仓储）
            var tasks = await _workflowTaskRepository.GetByAssigneeAsync(userId);
            var filtered = tasks.Where(t => t.Status == WorkflowTaskStatus.Pending || t.Status == WorkflowTaskStatus.InProgress);
            if (priority.HasValue) filtered = filtered.Where(t => t.Priority >= priority.Value);
            if (dueBefore.HasValue) filtered = filtered.Where(t => t.DueDate.HasValue && t.DueDate.Value <= dueBefore.Value);
            if (!string.IsNullOrWhiteSpace(keyword)) filtered = filtered.Where(t => (t.TaskName?.Contains(keyword) ?? false) || (t.NodeName?.Contains(keyword) ?? false));

            var total = filtered.Count();
            var items = filtered
                .OrderByDescending(t => t.Priority)
                .ThenBy(t => t.DueDate ?? DateTime.MaxValue)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .Select(t => new
                {
                    t.Id,
                    t.TaskName,
                    t.NodeName,
                    t.Status,
                    t.Priority,
                    t.DueDate,
                    t.CreatedAt,
                    t.UpdatedAt,
                    InstanceId = t.InstanceId
                })
                .ToList();

            return (items, total);
        }

        /// <summary>
        /// 我发起的实例
        /// </summary>
        public async Task<(IEnumerable<object> Items, int TotalCount)> GetMyInitiatedInstancesAsync(long userId, WorkflowInstanceStatus? status = null, int pageIndex = 1, int pageSize = 20)
        {
            var list = await _workflowInstanceRepository.GetByInitiatorAsync(userId);
            if (status.HasValue)
            {
                list = list.Where(i => i.Status == status.Value).ToList();
            }
            var total = list.Count;
            var items = list
                .OrderByDescending(i => i.CreatedAt)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .Select(i => new
                {
                    i.Id,
                    i.InstanceName,
                    i.Status,
                    i.CurrentNode,
                    i.CreatedAt,
                    i.UpdatedAt,
                    i.CompletedAt,
                    i.Priority
                })
                .ToList();
            return (items, total);
        }

        /// <summary>
        /// 刷新超时任务：将到期未完成的任务标记为超时
        /// </summary>
        public async Task<int> RefreshOverdueTasksAsync()
        {
            var now = DateTime.UtcNow;
            var candidates = await _workflowTaskRepository.FindAsync(t =>
                (t.Status == WorkflowTaskStatus.Pending || t.Status == WorkflowTaskStatus.InProgress)
                && t.DueDate.HasValue && t.DueDate.Value < now);
            int updated = 0;
            foreach (var t in candidates)
            {
                t.Status = WorkflowTaskStatus.Timeout;
                t.UpdatedAt = now;
                updated++;
            }
            if (updated > 0)
            {
                await _workflowTaskRepository.SaveChangesAsync();
            }
            return updated;
        }

        /// <summary>
        /// 获取工作流实例详情
        /// </summary>
        public async Task<object?> GetWorkflowInstanceDetailAsync(long instanceId)
        {
            try
            {
                var instance = await _workflowInstanceRepository.GetByIdAsync(instanceId);
                if (instance == null) return null;

                var tasks = await _workflowTaskRepository.FindAsync(t => t.InstanceId == instanceId);

                return new
                {
                    instance.Id,
                    instance.InstanceName,
                    instance.Status,
                    instance.CurrentNode,
                    instance.Priority,
                    instance.InitiatorId,
                    instance.CreatedAt,
                    instance.UpdatedAt,
                    instance.CompletedAt,
                    instance.Description,
                    ContextData = string.IsNullOrEmpty(instance.ContextData) 
                        ? new Dictionary<string, object>() 
                        : JsonSerializer.Deserialize<Dictionary<string, object>>(instance.ContextData),
                    Tasks = tasks.Select(t => new
                    {
                        t.Id,
                        t.TaskName,
                        t.NodeName,
                        t.AssigneeId,
                        t.Status,
                        t.Priority,
                        t.CreatedAt,
                        t.UpdatedAt,
                        t.CompletedAt,
                        t.DueDate,
                        t.Comments
                    }).ToList(),
                    Workflow = instance.Workflow != null ? new
                    {
                        instance.Workflow.Id,
                        instance.Workflow.Name
                    } : null
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流实例详情失败: {InstanceId}", instanceId);
                throw;
            }
        }

        /// <summary>
        /// 停止工作流实例
        /// </summary>
        public async Task<bool> StopWorkflowInstanceAsync(long instanceId, string? reason = null)
        {
            try
            {
                var instance = await _workflowInstanceRepository.GetByIdAsync(instanceId);
                if (instance == null) return false;

                if (instance.Status != WorkflowInstanceStatus.Running && instance.Status != WorkflowInstanceStatus.Paused)
                {
                    return false; // 只能停止运行中或暂停的实例
                }

                instance.Status = WorkflowInstanceStatus.Failed;
                instance.CompletedAt = DateTime.UtcNow;
                instance.UpdatedAt = DateTime.UtcNow;

                // 停止所有相关任务
                var pendingTasks = await _workflowTaskRepository.FindAsync(t => 
                    t.InstanceId == instanceId && 
                    (t.Status == WorkflowTaskStatus.Pending || t.Status == WorkflowTaskStatus.InProgress));

                foreach (var task in pendingTasks)
                {
                    task.Status = WorkflowTaskStatus.Cancelled;
                    task.UpdatedAt = DateTime.UtcNow;
                    task.Comments = AppendComment(task.Comments, $"因实例停止而取消: {reason}", 0, "system_stop");
                }

                await _workflowInstanceRepository.SaveChangesAsync();
                await _workflowTaskRepository.SaveChangesAsync();

                _logger.LogInformation("工作流实例已停止: {InstanceId}, 原因: {Reason}", instanceId, reason);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "停止工作流实例失败: {InstanceId}", instanceId);
                throw;
            }
        }

        /// <summary>
        /// 重试工作流实例
        /// </summary>
        public async Task<bool> RetryWorkflowInstanceAsync(long instanceId)
        {
            try
            {
                var instance = await _workflowInstanceRepository.GetByIdAsync(instanceId);
                if (instance == null) return false;

                if (instance.Status != WorkflowInstanceStatus.Failed)
                {
                    return false; // 只能重试失败的实例
                }

                instance.Status = WorkflowInstanceStatus.Running;
                instance.CompletedAt = null;
                instance.UpdatedAt = DateTime.UtcNow;

                // 重置失败的任务状态
                var failedTasks = await _workflowTaskRepository.FindAsync(t => 
                    t.InstanceId == instanceId && 
                    (t.Status == WorkflowTaskStatus.Rejected || t.Status == WorkflowTaskStatus.Cancelled || t.Status == WorkflowTaskStatus.Timeout));

                foreach (var task in failedTasks)
                {
                    task.Status = WorkflowTaskStatus.Pending;
                    task.UpdatedAt = DateTime.UtcNow;
                    task.CompletedAt = null;
                    task.Comments = AppendComment(task.Comments, "实例重试，任务状态重置", 0, "system_retry");
                }

                await _workflowInstanceRepository.SaveChangesAsync();
                await _workflowTaskRepository.SaveChangesAsync();

                _logger.LogInformation("工作流实例重试成功: {InstanceId}", instanceId);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重试工作流实例失败: {InstanceId}", instanceId);
                throw;
            }
        }

        /// <summary>
        /// 批量操作工作流实例
        /// </summary>
        public async Task<BatchOperationResult> BatchOperateInstancesAsync(List<long> instanceIds, string operation, string? reason = null)
        {
            var result = new BatchOperationResult();

            foreach (var instanceId in instanceIds)
            {
                try
                {
                    bool success = operation.ToLower() switch
                    {
                        "stop" => await StopWorkflowInstanceAsync(instanceId, reason),
                        "retry" => await RetryWorkflowInstanceAsync(instanceId),
                        "delete" => await DeleteWorkflowInstanceAsync(instanceId),
                        _ => false
                    };

                    if (success)
                    {
                        result.SuccessIds.Add(instanceId);
                        result.SuccessCount++;
                    }
                    else
                    {
                        result.FailedOperations.Add(new OperationFailure
                        {
                            InstanceId = instanceId,
                            ErrorMessage = $"操作失败: {operation}"
                        });
                        result.FailCount++;
                    }
                }
                catch (Exception ex)
                {
                    result.FailedOperations.Add(new OperationFailure
                    {
                        InstanceId = instanceId,
                        ErrorMessage = ex.Message
                    });
                    result.FailCount++;
                    _logger.LogWarning(ex, "批量操作实例失败: {InstanceId}, 操作: {Operation}", instanceId, operation);
                }
            }

            _logger.LogInformation("批量操作完成, 操作: {Operation}, 成功: {SuccessCount}, 失败: {FailCount}", 
                operation, result.SuccessCount, result.FailCount);

            return result;
        }

        /// <summary>
        /// 删除工作流实例
        /// </summary>
        private async Task<bool> DeleteWorkflowInstanceAsync(long instanceId)
        {
            try
            {
                var instance = await _workflowInstanceRepository.GetByIdAsync(instanceId);
                if (instance == null) return false;

                // 只能删除已完成或失败的实例
                if (instance.Status == WorkflowInstanceStatus.Running || instance.Status == WorkflowInstanceStatus.Paused)
                {
                    return false;
                }

                // 删除相关任务
                var tasks = await _workflowTaskRepository.FindAsync(t => t.InstanceId == instanceId);
                foreach (var task in tasks)
                {
                    await _workflowTaskRepository.DeleteAsync(task);
                }

                // 删除实例
                await _workflowInstanceRepository.DeleteAsync(instance);
                await _workflowInstanceRepository.SaveChangesAsync();
                await _workflowTaskRepository.SaveChangesAsync();

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除工作流实例失败: {InstanceId}", instanceId);
                throw;
            }
        }

    #endregion

    #region Workflow Versioning

        public async Task<WorkflowVersionDto> CreateVersionAsync(long workflowId, string? tag = null, string? description = null, long? userId = null)
        {
            var workflow = await _workflowRepository.GetByIdAsync(workflowId) ?? throw new ArgumentException($"工作流不存在: {workflowId}");

            for (var attempt = 0; attempt < Math.Max(1, _versioningMaxRetries + 1); attempt++)
            {
                var nextVersion = await _workflowVersionRepository.GetNextVersionNumberAsync(workflowId);
                var version = new WorkflowVersion
                {
                    WorkflowId = workflowId,
                    Version = nextVersion,
                    Tag = tag,
                    Steps = workflow.Steps,
                    Conditions = workflow.Conditions,
                    Description = description,
                    CreatedBy = userId ?? 0,
                    CreatedAt = DateTime.UtcNow
                };

                try
                {
                    using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        await _workflowVersionRepository.AddAsync(version);
                        workflow.CurrentVersion = nextVersion;
                        workflow.UpdatedAt = DateTime.UtcNow;
                        await _workflowRepository.SaveChangesAsync();
                        await _workflowVersionRepository.SaveChangesAsync();
                        scope.Complete();
                    }

                    _logger.LogInformation("创建工作流版本成功: Workflow={WorkflowId}, Version=v{Version}", workflowId, nextVersion);
                    return MapToDto(version);
                }
                catch (DbUpdateException ex) when (IsUniqueConstraintViolation(ex))
                {
                    _logger.LogWarning(ex, "版本唯一索引冲突，准备重试: Workflow={WorkflowId}", workflowId);
                    if (attempt == _versioningMaxRetries)
                    {
                        _logger.LogError(ex, "版本创建失败（达到最大重试次数）: Workflow={WorkflowId}", workflowId);
                        if (_monitorService != null)
                        {
                            _ = _monitorService.SendAlertAsync($"Workflow versioning unique conflict exhausted retries: workflow={workflowId}");
                        }
                    }
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    _logger.LogWarning(ex, "创建版本时发生并发冲突，准备重试: Workflow={WorkflowId}", workflowId);
                    if (attempt == _versioningMaxRetries)
                    {
                        _logger.LogError(ex, "版本创建失败（达到最大重试次数）: Workflow={WorkflowId}", workflowId);
                        if (_monitorService != null)
                        {
                            _ = _monitorService.SendAlertAsync($"Workflow versioning concurrency exhausted retries: workflow={workflowId}");
                        }
                    }
                }

                var jitter = _versioningJitterMs > 0 ? Random.Shared.Next(0, _versioningJitterMs) : 0;
                var delayMs = _versioningBaseBackoffMs * (int)Math.Pow(2, attempt) + jitter;
                await Task.Delay(delayMs);
            }

            throw new InvalidOperationException("创建工作流版本失败：遇到并发或唯一约束冲突");
        }

        public async Task<IEnumerable<WorkflowVersionDto>> GetVersionsAsync(long workflowId)
        {
            var list = await _workflowVersionRepository.GetVersionsAsync(workflowId);
            return list.Select(MapToDto).ToList();
        }

        public async Task<WorkflowVersionDto?> GetVersionAsync(long workflowId, int version)
        {
            var entity = await _workflowVersionRepository.GetVersionAsync(workflowId, version);
            return entity == null ? null : MapToDto(entity);
        }

        public async Task<bool> RollbackToVersionAsync(long workflowId, int version, long? userId = null, string? reason = null)
        {
            var target = await _workflowVersionRepository.GetVersionAsync(workflowId, version);
            if (target == null) return false;

            var workflow = await _workflowRepository.GetByIdAsync(workflowId) ?? throw new ArgumentException($"工作流不存在: {workflowId}");

            workflow.Steps = target.Steps;
            workflow.Conditions = target.Conditions;
            workflow.UpdatedAt = DateTime.UtcNow;

            for (var attempt = 0; attempt < Math.Max(1, _versioningMaxRetries + 1); attempt++)
            {
                var next = await _workflowVersionRepository.GetNextVersionNumberAsync(workflowId);
                var rollbackVersion = new WorkflowVersion
                {
                    WorkflowId = workflowId,
                    Version = next,
                    Tag = target.Tag,
                    Steps = target.Steps,
                    Conditions = target.Conditions,
                    Description = $"Rollback from v{version}" + (string.IsNullOrWhiteSpace(reason) ? string.Empty : $": {reason}"),
                    CreatedBy = userId ?? 0,
                    CreatedAt = DateTime.UtcNow
                };

                try
                {
                    using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        await _workflowVersionRepository.AddAsync(rollbackVersion);
                        workflow.CurrentVersion = next;
                        await _workflowRepository.SaveChangesAsync();
                        await _workflowVersionRepository.SaveChangesAsync();
                        scope.Complete();
                    }

                    _logger.LogInformation("工作流已回滚: Workflow={WorkflowId}, From=v{From} To=v{To}", workflowId, version, next);
                    return true;
                }
                catch (DbUpdateException ex) when (IsUniqueConstraintViolation(ex))
                {
                    _logger.LogWarning(ex, "回滚创建版本时唯一索引冲突，准备重试: Workflow={WorkflowId}", workflowId);
                    if (attempt == _versioningMaxRetries)
                    {
                        _logger.LogError(ex, "回滚失败（达到最大重试次数）: Workflow={WorkflowId}", workflowId);
                        if (_monitorService != null)
                        {
                            _ = _monitorService.SendAlertAsync($"Workflow rollback unique conflict exhausted retries: workflow={workflowId}");
                        }
                    }
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    _logger.LogWarning(ex, "回滚时发生并发冲突，准备重试: Workflow={WorkflowId}", workflowId);
                    if (attempt == _versioningMaxRetries)
                    {
                        _logger.LogError(ex, "回滚失败（达到最大重试次数）: Workflow={WorkflowId}", workflowId);
                        if (_monitorService != null)
                        {
                            _ = _monitorService.SendAlertAsync($"Workflow rollback concurrency exhausted retries: workflow={workflowId}");
                        }
                    }
                }

                var jitter = _versioningJitterMs > 0 ? Random.Shared.Next(0, _versioningJitterMs) : 0;
                var delayMs = _versioningBaseBackoffMs * (int)Math.Pow(2, attempt) + jitter;
                await Task.Delay(delayMs);
            }

            return false;
        }

        /// <summary>
        /// 跨数据库提供商识别唯一约束冲突
        /// 支持 SQL Server / PostgreSQL / MySQL
        /// </summary>
        private static bool IsUniqueConstraintViolation(DbUpdateException ex)
        {
            Exception? cur = ex;
            while (cur != null)
            {
                // SQL Server
                if (cur is Microsoft.Data.SqlClient.SqlException mssql && (mssql.Number == 2627 || mssql.Number == 2601))
                    return true;

                // PostgreSQL
                if (cur is Npgsql.PostgresException pg && string.Equals(pg.SqlState, "23505", StringComparison.Ordinal))
                    return true;

                // MySQL (Pomelo/MySqlConnector)
                if (cur is MySqlConnector.MySqlException my && my.Number == 1062)
                    return true;

                // 兜底：基于消息文本的弱匹配
                if (cur.Message.IndexOf("unique", StringComparison.OrdinalIgnoreCase) >= 0 ||
                    cur.Message.IndexOf("duplicate", StringComparison.OrdinalIgnoreCase) >= 0 ||
                    cur.Message.IndexOf("约束", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    return true;
                }

                cur = cur.InnerException;
            }
            return false;
        }

        private static WorkflowVersionDto MapToDto(WorkflowVersion v) => new()
        {
            Id = v.Id,
            WorkflowId = v.WorkflowId,
            Version = v.Version,
            Tag = v.Tag,
            Steps = v.Steps,
            Conditions = v.Conditions,
            Description = v.Description,
            CreatedBy = v.CreatedBy,
            CreatedAt = v.CreatedAt
        };
        #endregion
    }
}
